package com.norma.netty.study.netty.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangchaofeng
 * @date 2020/10/4
 * @description 心跳
 */
public class NettyHeartbeatServer {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))//在bossGroup增加日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //IdleStateHandler 空闲状态处理器
                            // long readerIdleTime 表示多长时间没有读就会发送一个心跳检测包检测是否连接
                            // long writerIdleTime 表示多长时间没有写就会发送一个心跳检测包检测是否连接
                            // long allIdleTime 表示多长时间没有读写就会发送一个心跳检测包检测是否连接
                            pipeline.addLast(new IdleStateHandler(3,
                                    5, 7, TimeUnit.SECONDS));
                            //当IdleStateEvent事件触发后，就会传递给管道的下一个handler的userEventTrigger处理
                            pipeline.addLast(new NettyHeartbeatServerHandler());//定义一个对空闲处理的自定义处理
                        }
                    });
            ChannelFuture sync = serverBootstrap.bind(8888).sync();
            sync.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }

}
